package sctu.edu.java.year2016.team02.project.service.UI;

import javax.swing.*;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * Created by Eoly on 2016/6/16.
 */
public class StartAndClose implements Runnable{
    //内部私有变量
    private JLabel tip;
    private JTextArea state;
    private boolean isConn=false;
    private ServerSocket serverSocket ;
    private JRadioButton startService;
    private Socket socket;

    //公开静态变量
    public static String ipAddress="127.0.0.1";
    public static int port=8888;
    public static boolean isStart;

    //构造方法
    public StartAndClose(JLabel tip, JTextArea state,JRadioButton startService,boolean isStart){
        this.tip=tip;
        this.state=state;
        this.isStart = isStart;
        this.startService = startService;
    }

    //通过此方法开启服务端服务
    private void ServerStart() throws InterruptedException {
        startService.setEnabled(false);
        try {
            serverSocket = new ServerSocket();
            serverSocket.bind(new InetSocketAddress(ipAddress, port));
            setStateText("服务器创建成功",serverSocket.getLocalSocketAddress().toString());
            System.out.println("服务器创建成功\n" + serverSocket.getLocalSocketAddress());
            setStateText("等待客户端连接...", "/local");
        } catch (IOException e) {
            setStateText(e.getMessage(), "/local");
            startService.setSelected(false);
            ipSet.setIp();
        }
        startService.setEnabled(true);
        while (isStart) {
            try {//若连接成功则创建一个进程和套接字连接服务端
                serverSocket.setSoTimeout(10000);
                socket = serverSocket.accept();
                Thread thr = new Thread( new SocketRunnable(socket,state));
                thr.start();
            } catch (IOException e) {
                isConn = false;
            }
            if(!isStart) {
                try {
                    serverSocket.close();
                    setStateText("服务已关闭...","/local");
                    startService.setEnabled(true);
                } catch (IOException e) {
                    setStateText("关闭服务失败正在重试...","/local");
                }
            }
        }
    }

    //对主界面添加提示文字
    public void setStateText(String text,String user) {
        state.setText(state.getText() +" ["+user+"]  "+ text + "\n");
        state.setCaretPosition(state.getText().length());
    }

    @Override
    public void run() {
        try {
            ServerStart();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
